package io.gitee.zhangbinhub.admin.resource.server.tools

import cn.dev33.satoken.oauth2.exception.SaOAuth2Exception
import io.gitee.zhangbinhub.acp.cloud.resource.server.constant.AcpCloudResourceServerConstant
import io.gitee.zhangbinhub.acp.cloud.resource.server.tools.TokenTools
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.admin.resource.server.vo.TokenUserInfoVo
import org.bouncycastle.util.encoders.Base64
import org.noear.snack4.ONode

object TokenInfoTools {
    @JvmStatic
    @Throws(SaOAuth2Exception::class)
    fun encryptUserInfo(userInfoVo: TokenUserInfoVo): String = try {
        Base64.toBase64String(ONode.serialize(userInfoVo).toByteArray(CommonTools.getDefaultCharset()))
    } catch (e: Exception) {
        throw SaOAuth2Exception(e.message)
    }

    @JvmStatic
    @Throws(SaOAuth2Exception::class)
    fun decryptUserInfo(ciphertext: String): TokenUserInfoVo = try {
        ONode.deserialize(
            String(Base64.decode(ciphertext), CommonTools.getDefaultCharset()), TokenUserInfoVo::class.java
        )
    } catch (e: Exception) {
        throw SaOAuth2Exception(e.message)
    }

    @JvmStatic
    @Throws(SaOAuth2Exception::class)
    fun getUserInfoFromToken(accessToken: String? = null): TokenUserInfoVo =
        TokenTools.getAccessTokenModel(accessToken)?.let { atm ->
            decryptUserInfo(atm.extraData[AcpCloudResourceServerConstant.TOKEN_CLAIMS_USER_INFO].toString())
        } ?: TokenUserInfoVo()
}